package org.timemachine.action.facadeBean;

import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.timemachine.action.facade.ChangeInfoFacade;
import org.timemachine.model.base.ChangeInfo;

@Stateless
public class ChangeInfoFacadeBean implements ChangeInfoFacade {

	@PersistenceContext
	private EntityManager entityManager;


	@Override
	public void createChangeInfo(ChangeInfo changeInfo) {		
		entityManager.persist(changeInfo);
	}

	@Override
	public void remove(ChangeInfo changeInfo) {		
		entityManager.remove(changeInfo);
	}

	@Override
	public ChangeInfo findById(Long changeInfoId) {
		return entityManager.find(ChangeInfo.class, changeInfoId);
	}

	@Override
	public ChangeInfo findReferenceById(Long changeInfoId) {
		return entityManager.find(ChangeInfo.class, changeInfoId);
	}

	@Override
	public ChangeInfo findInfiniteInstance() {
		
		 ChangeInfo infinite = findReferenceById(0L);
		 if (infinite==null || infinite.getId()==null) {
			 infinite = new ChangeInfo();
			 infinite.setChangeTimeStamp(new Date());
			 infinite.setChangeUser("timemachine");
			 infinite.setChannel("system");
			 infinite.setId(0L);
			 entityManager.merge(infinite);
		 }
		 return infinite;
	}

	public ChangeInfo merge(ChangeInfo changeInfo) {
		return entityManager.merge(changeInfo);
	}

}
